import axios from 'axios'
// 导入饿了吗消息提示组件=》请求报错使用它提示报错信息
import { Message } from 'element-ui'

// // 导入vuex获取token数据
import store from '@/store'
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 请求正常
    // do something before request is sent

    // 在这个位置需要统一的去注入token
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 如果token存在 注入token
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config // 必须返回配置
  },
  error => {
    // 请求错误
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 响应拦截器
service.interceptors.response.use(
  response => {
    // 从axios的data中解构出来必要的字段
    const { success, message, data } = response.data
    // 如果success为true,直接返回data即可
    if (success) {
      return data
      // return response
    } else {
      // 如果success为false 业务出错,直接触发reject 组件调用接口可通过try/catch捕获错误
      return Promise.reject(new Error(message))
    }

    // const res = response.data

    // // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  error => {
    console.log('err' + error) // for debug
    if (error.response && error.response.status === 401) {
      if (router.currentRoute.path === '/login') return
      // 退出登录 action 删除token和用户信息
      store.dispatch('user/logout')
      // router.replace(`/login?redirect=${router.currentRoute.path}`)
      router.replace('/login?redirect=' + router.currentRoute.path)
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
